﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using Medicalsystem.MCP.FormDesigner.Common;
using Medicalsystem.MCP.FormDesigner.Ctl;
using Medicalsystem.MCP.FormDesigner.Define;
using Medicalsystem.MCP.FormDesigner.Interface;

namespace Medicalsystem.MCP.FormDesigner
{
    /// <summary>
    /// 对模版的操作管理
    /// </summary>
    public class ModelDesign : Model
    {
        private ctl_ModelDesignObject _modeDesignObject;

        private Rectangle _mouseRect = Rectangle.Empty;

        //private UndoRedo _undoRedo = null;
        private UIContainerHandler _ctrlUIContainerHandler = null;      //UI控件容器管理者

        private ComContainerHandler _ctrlComContainerHandler = null;    //组件类控件容器管理者
        private CtrlMngDesign _ctrlMngDesignFocused = null;             //当前焦点控件管理者

        ////////////处理控件的选取/////////////
        private List<CtrlMngDesign> _selectList = null; //保存被选中的控件(控件捏手对应关系)

        private List<CtrlMngDesign> _tempSelect = null; //保存临时值（当选取多个控件时用到

        ///////////////////////////////////////

        public bool CtrlKeyDown = false;
        public int CurrentTableIndexValue = -1;
        public bool BeginMove = false;
        public bool PropertyChangeAvail = true; //某些情况下 - 控件属性改变事件不需要执行

        private string _fileName = string.Empty; //模板关联的文件名

        /// <summary>
        /// 这里Owner使用的是Control类型，容器可以是Winform,Panel,GroupBox等控件
        /// </summary>
        /// <param name="modeDesignObjec"></param>
        /// <param name="instanceID">实例编号</param>
        public ModelDesign(ctl_ModelDesignObject modeDesignObject)
            : base(modeDesignObject.ModelID, modeDesignObject.ModelForm)
        {
            this._modeDesignObject = modeDesignObject;

            this._ctrlComContainerHandler = new ComContainerHandler(_modeDesignObject.Container_Com, this);

            _ctrlUIContainerHandler = new UIContainerHandler(modeDesignObject.ModelForm, null, this);

            //所有控件事件 都会传递到 Form 上执行
            this.Owner.KeyDown += new KeyEventHandler(Owner_KeyDown);
            this.Owner.KeyUp += new KeyEventHandler(Owner_KeyUp);

            //_undoRedo = new UndoRedo(Owner);
            //_undoRedo.EventBindEvent+=new EventBindHandler(OnEventBindEvent);
            _selectList = new List<CtrlMngDesign>();
            _tempSelect = new List<CtrlMngDesign>();
        }

        #region 属性

        /// <summary>
        /// 模板关联文件
        /// </summary>
        public string FileName
        {
            get { return _fileName; }
            set { _fileName = value; }
        }

        /// <summary>
        /// UI类控件容器
        /// </summary>
        public UIContainerHandler CtrlUIContainerHandler
        {
            get { return _ctrlUIContainerHandler; }
        }

        /// <summary>
        /// 组件类控件容器
        /// </summary>
        public ComContainerHandler CtrlComContainerHandler
        {
            get { return _ctrlComContainerHandler; }
        }

        /// <summary>
        /// 焦点控件
        /// </summary>
        public CtrlMngDesign CtrlMngDesignFocused
        {
            get { return _ctrlMngDesignFocused; }
            set
            {
                if (value == null && _ctrlMngDesignFocused != null)
                {
                    _ctrlMngDesignFocused.Focused = false;
                }
                if (value != null)
                {
                    value.Focused = true;
                }

                _ctrlMngDesignFocused = value;
            }
        }

        /// <summary>
        /// 模板
        /// </summary>
        public System.Windows.Forms.Form Owner
        {
            get { return this._modeDesignObject.ModelForm; }
        }

        public ctl_ModelDesignObject ModeDesignObject
        {
            get { return _modeDesignObject; }
        }

        // <summary>
        // 选取控件
        // </summary>
        public List<CtrlMngDesign> SelectList
        {
            get { return _selectList; }
        }

        #endregion 属性

        #region InitControls

        protected override void CreateControls()
        {
            this.Controls = new CtrlCollectionDesign(this);
        }

        #endregion InitControls

        #region 键盘按键响应

        /// <summary>
        /// 焦点在模板中的控件时，同样会引发模板的KeyDown事件
        /// 控件上的KeyDown事件 会传递到模板上
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Owner_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            try
            {
                switch (e.KeyCode)
                {
                    case Keys.ControlKey:
                        this.CtrlKeyDown = true;
                        break;

                    case Keys.A:
                    case Keys.C:
                    case Keys.V:
                    case Keys.Z:
                    case Keys.F4:
                        SingleList.Instance.OnMessageEvent(e, MessageType.KeyEvent);
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                TryCustomException.TransactException(ex);
            }
        }

        /// <summary>
        /// 处理键盘事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Owner_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == System.Windows.Forms.Keys.ControlKey)
                {
                    this.CtrlKeyDown = false;
                }
            }
            catch (Exception ex)
            {
                TryCustomException.TransactException(ex);
            }
        }

        #endregion 键盘按键响应

        #region 控件选取方法

        /// <summary>
        /// 选取新增控件-
        /// 用于控件的点选
        /// </summary>
        /// <param name="ctrlHandler"></param>
        public void SelectListAdd(CtrlMngDesign ctrlHandler)
        {
            try
            {
                if (_selectList.IndexOf(ctrlHandler) >= 0)
                {
                    if (this.CtrlKeyDown)
                    {
                        //处理反选

                        foreach (CtrlMngDesign ch in _selectList)
                        {
                            //处理焦点和非焦点情况
                            if (ch == ctrlHandler)
                            {
                                _selectList.Remove(ch);

                                if (ctrlHandler == CtrlMngDesignFocused)
                                {
                                    //如果是焦点控件,直接随机设置一个控件为焦点控件
                                    if (_selectList.Count > 0)
                                    {
                                        SetControlFocus(_selectList[0], true, false);
                                    }
                                    else
                                    {
                                        CtrlMngDesignFocused = null;
                                    }
                                }

                                break;
                            }
                        }
                    }
                    else
                    {
                        //设为焦点
                        SetControlFocus(ctrlHandler, true, false);
                    }
                }
                else
                {
                    //选区外选取
                    if (this.CtrlKeyDown && CtrlMngDesignFocused != null && CtrlMngDesignFocused.ParentContainer == ctrlHandler.ParentContainer)
                    {
                        SetControlFocus(ctrlHandler, true, true);
                    }
                    else
                    {
                        SelectListClear();
                        SetControlFocus(ctrlHandler, true, true);
                    }
                }
            }
            catch (Exception ex)
            {
                TryCustomException.TransactException(ex);
            }
        }

        /// <summary>
        /// 添加多个选取
        /// 添加完后 一定要调用SelectListAppendEnd()
        /// </summary>
        /// <param name="ctrlHandler"></param>
        public void SelectListAppend(CtrlMngDesign ctrlHandler)
        {
            try
            {
                this._tempSelect.Add(ctrlHandler);
            }
            catch (Exception ex)
            {
                TryCustomException.TransactException(ex);
            }
        }

        /// <summary>
        /// 呈现选取项
        /// 在SelectListAppend 后使用
        /// </summary>
        /// <param name="ctrlKeyDown">恢复CtrlKey状态 --如快捷健使用该方法时 需要复原</param>
        public void SelectListAppendEnd(bool ctrlKeyDown)
        {
            this.CtrlKeyDown = ctrlKeyDown;

            SelectListAppendEnd();
        }

        /// <summary>
        /// 呈现选取项
        /// 在SelectListAppend 后使用
        /// </summary>
        public void SelectListAppendEnd()
        {
            try
            {
                if (this.CtrlKeyDown && CtrlMngDesignFocused != null && (_tempSelect.Count == 0 || _tempSelect[0].ParentContainer == CtrlMngDesignFocused.ParentContainer))
                {
                    bool removeFocus = false;

                    foreach (CtrlMngDesign ch in _tempSelect)
                    {
                        int index = _selectList.IndexOf(ch);
                        if (index < 0)
                        {
                            SetControlFocus(ch, false, true);
                        }
                        else
                        {
                            //移除选项 如果移除了焦点选项 要重设焦点
                            if (_selectList[index] == _ctrlMngDesignFocused)
                            {
                                removeFocus = true;
                            }

                            _selectList.RemoveAt(index);
                        }
                    }

                    if (removeFocus)
                    {
                        //移除了焦点 重设焦点
                        if (_selectList.Count > 0)
                        {
                            SetControlFocus(_selectList[0], true, false);
                        }
                    }
                }
                else
                {
                    SelectListClear();
                    CtrlMngDesign ch_Top = null;

                    foreach (CtrlMngDesign ch in _tempSelect)
                    {
                        SetControlFocus(ch, false, true);

                        if (ch_Top != null)
                        {
                            if (ch_Top.Owner.Top > ch_Top.Owner.Top)
                            {
                                ch_Top = ch;
                            }
                        }
                        else
                        {
                            ch_Top = ch;
                        }
                    }

                    if (ch_Top != null)
                    {
                        SetControlFocus(ch_Top, true, false);
                    }
                }

                _tempSelect.Clear();
            }
            catch (Exception ex)
            {
                TryCustomException.TransactException(ex);
            }
        }

        /// <summary>
        /// 清除选取列表
        /// </summary>
        public void SelectListClear()
        {
            try
            {
                _selectList.Clear();

                //此处对原容器进行一次刷新 清楚虚线框
                if (CtrlMngDesignFocused != null)
                {
                    CtrlMngDesignFocused.ParentContainer.Container.Refresh();
                }

                CtrlMngDesignFocused = null;
            }
            catch (Exception ex)
            {
                TryCustomException.TransactException(ex);
            }
        }

        /// <summary>
        /// 设置控件焦点
        /// </summary>
        /// <param name="ctrlHandler"></param>
        /// <param name="focused">是否设置焦点</param>
        /// <param name="selectAdd">是否添加到选取列表</param>
        private void SetControlFocus(CtrlMngDesign ctrlHandler, bool focused, bool selectAdd)
        {
            if (selectAdd)
            {
                _selectList.Add(ctrlHandler);
            }

            if (focused && CtrlMngDesignFocused != ctrlHandler)
            {
                CtrlMngDesignFocused = ctrlHandler;
                SingleList.Instance.OnMessageEvent(ctrlHandler, MessageType.ControlFocus);
            }
        }

        #endregion 控件选取方法

        #region 选取框方法

        private void ResizeToRectangle(Point p, FrameStyle fs)
        {
            DrawRectangle(fs);
            _mouseRect.Width = p.X - _mouseRect.Left;
            _mouseRect.Height = p.Y - _mouseRect.Top;
            DrawRectangle(fs);
        }

        private void DrawRectangle(FrameStyle fs)
        {
            Rectangle rect = this._modeDesignObject.ModelForm.RectangleToScreen(_mouseRect);
            ControlPaint.DrawReversibleFrame(rect, Color.Transparent, fs);
        }

        #endregion 选取框方法

        /// <summary>
        /// 删除控件
        /// </summary>
        /// <param name="ctrl"></param>
        public void RemoveControl(CtrlMngDesign ctrl)
        {
            if (ctrl.Ctrl is ICtrlContainer)
            {
                foreach (ContainerHandler container in ctrl.ContainerHandlerList)
                {
                    for (int i = container.Controls.Count - 1; i >= 0; i--)
                    {
                        RemoveControl(container.Controls[i]);
                    }
                }
            }

            ctrl.ParentContainer.Controls.Remove(ctrl);
            Controls.Ctrls.Remove((CtrlMng)ctrl);
            ctrl.Dispose();
        }

        public void Refresh()
        {
            this._modeDesignObject.Refresh();
        }

        /// <summary>
        /// 模板重置为初始状态 - 即清除所有内容
        /// </summary>
        public void Reset()
        {
            _ctrlMngDesignFocused = null;
            _selectList.Clear();
            _tempSelect.Clear();
            this.Controls.Ctrls.Clear();

            _ctrlUIContainerHandler.Reset();
            _ctrlComContainerHandler.Reset();

            this.Refresh();
        }
    }
}